package culton.android.server;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class WebServiceHandler {

	//private static String domain = "http://10.0.2.2:8888/";
	private static String domain = "http://cultonserver.appspot.com/";
	
	/**
	 * Get movies from a given cinema.
	 * This method receives a cinema id and gets all movies that belong to this cinema.
	 * The number of movies returned is determined by the count parameter. 
	 * If count = -1, all movies are returned.
	 * **/
	public static ArrayList<String> getMovies(int count, String cinema_id) {
		ArrayList<String> movies = new ArrayList<String>();		
		String method = domain + "cinemas/" + cinema_id + "/movies";
		
		try {
			//Connect to webservice and get response
			JSONObject result = RestClient.getResponse(method);

			//Fixme: movies need to be ordered by opening date desc
			JSONArray moviesList = result.getJSONArray("movies");

			//It uses the smaller between count and moviesList.length to determine 
			//the number of movies to return 
			int max = count;
			if (moviesList.length() < count || max == -1)
				max = moviesList.length();
			
			for (int i = 0; i < max; i++) {
				JSONObject movieObj = moviesList.getJSONObject(i);
				String movieName = movieObj.getString("name");
				movies.add(movieName);
			}		

		} catch (JSONException e) {
			e.printStackTrace();
		}		
		return movies;
	}
	
	/**
	 * Get a movie showtime in a cinema.
	 * It receives a movie id and a cinema id. 
	 **/
	public static ArrayList<String> getShowtimes(String cinema_id, String movie_id) {
		ArrayList<String> showtimes = new ArrayList<String>();
		String method = domain + "cinemas/" + cinema_id + "/movies/" + movie_id;
		Log.i("method", method);
		JSONObject result = new JSONObject();
		try {
			//Connect to webservice and get response
			result = RestClient.getResponse(method);
			
			JSONArray showtimeDubbed = result.getJSONArray("showtimeDubbed");
			JSONArray showtimeSubtitled = result.getJSONArray("showtimeSubtitled");
			JSONArray showtime3DDubbed = result.getJSONArray("showtime3DDubbed");
			JSONArray showtime3DSubtitled = result.getJSONArray("showtime3DSubtitled");

			for (int i = 0; i < showtimeDubbed.length(); i++)
				showtimes.add(showtimeDubbed.getString(i) + "(DUB)");
			
			for (int i = 0; i < showtimeSubtitled.length(); i++)
				showtimes.add(showtimeSubtitled.getString(i));

			for (int i = 0; i < showtime3DDubbed.length(); i++)
				showtimes.add(showtime3DSubtitled.getString(i) + "(3D DUB)");
			
			for (int i = 0; i < showtimeSubtitled.length(); i++) 
				showtimes.add(showtime3DDubbed.getString(i));

		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return showtimes;
	}	
	
}
